import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
from typing import Optional

# 日志配置
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper()
LOG_DIR = os.getenv('LOG_DIR', 'logs')
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

# 确保日志目录存在
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

def get_logger(name: str, level: Optional[str] = None) -> logging.Logger:
    """获取日志记录器
    
    Args:
        name: 日志记录器名称
        level: 日志级别，如果不指定则使用环境变量LOG_LEVEL
    
    Returns:
        配置好的日志记录器
    """
    logger = logging.getLogger(name)
    
    # 如果已经配置过，直接返回
    if logger.handlers:
        return logger
    
    # 设置日志级别
    log_level = level or LOG_LEVEL
    logger.setLevel(getattr(logging, log_level))
    
    # 创建格式化器
    formatter = logging.Formatter(LOG_FORMAT, LOG_DATE_FORMAT)
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(getattr(logging, log_level))
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # 文件处理器 - 按大小轮转
    file_handler = RotatingFileHandler(
        filename=os.path.join(LOG_DIR, f'{name}.log'),
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    file_handler.setLevel(getattr(logging, log_level))
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    
    # 错误日志文件处理器 - 按时间轮转
    error_handler = TimedRotatingFileHandler(
        filename=os.path.join(LOG_DIR, f'{name}_error.log'),
        when='midnight',
        interval=1,
        backupCount=30,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    logger.addHandler(error_handler)
    
    # 防止日志传播到根记录器
    logger.propagate = False
    
    return logger

def setup_application_logging():
    """设置应用程序日志配置"""
    # 配置根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, LOG_LEVEL))
    
    # 如果已经有处理器，清除它们
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 创建应用程序日志记录器
    app_logger = get_logger('blockchain_middleware')
    
    # 设置第三方库的日志级别
    logging.getLogger('pymongo').setLevel(logging.WARNING)
    logging.getLogger('urllib3').setLevel(logging.WARNING)
    logging.getLogger('requests').setLevel(logging.WARNING)
    
    app_logger.info("Application logging configured")
    return app_logger

def log_function_call(func):
    """装饰器：记录函数调用"""
    def wrapper(*args, **kwargs):
        logger = get_logger(func.__module__)
        logger.debug(f"Calling function: {func.__name__}")
        try:
            result = func(*args, **kwargs)
            logger.debug(f"Function {func.__name__} completed successfully")
            return result
        except Exception as e:
            logger.error(f"Function {func.__name__} failed: {str(e)}")
            raise
    return wrapper

def log_performance(func):
    """装饰器：记录函数性能"""
    import time
    
    def wrapper(*args, **kwargs):
        logger = get_logger(func.__module__)
        start_time = time.time()
        
        try:
            result = func(*args, **kwargs)
            execution_time = time.time() - start_time
            logger.info(f"Function {func.__name__} executed in {execution_time:.4f} seconds")
            return result
        except Exception as e:
            execution_time = time.time() - start_time
            logger.error(f"Function {func.__name__} failed after {execution_time:.4f} seconds: {str(e)}")
            raise
    
    return wrapper

class StructuredLogger:
    """结构化日志记录器"""
    
    def __init__(self, name: str):
        self.logger = get_logger(name)
    
    def log_event(self, event_type: str, message: str, **kwargs):
        """记录结构化事件"""
        log_data = {
            'event_type': event_type,
            'message': message,
            'timestamp': datetime.utcnow().isoformat(),
            **kwargs
        }
        
        self.logger.info(f"EVENT: {log_data}")
    
    def log_transaction(self, tx_hash: str, chain_id: str, status: str, **kwargs):
        """记录交易事件"""
        self.log_event(
            'transaction',
            f"Transaction {status}",
            tx_hash=tx_hash,
            chain_id=chain_id,
            status=status,
            **kwargs
        )
    
    def log_api_request(self, method: str, endpoint: str, status_code: int, 
                       response_time: float, **kwargs):
        """记录API请求"""
        self.log_event(
            'api_request',
            f"{method} {endpoint} - {status_code}",
            method=method,
            endpoint=endpoint,
            status_code=status_code,
            response_time=response_time,
            **kwargs
        )
    
    def log_error(self, error_type: str, error_message: str, **kwargs):
        """记录错误事件"""
        self.log_event(
            'error',
            error_message,
            error_type=error_type,
            **kwargs
        )
        
        # 同时使用ERROR级别记录
        self.logger.error(f"{error_type}: {error_message}")

# 全局结构化日志记录器实例
structured_logger = StructuredLogger('blockchain_middleware')